#include "musicslider.h"
#include "ui_musicslider.h"

#include <QMouseEvent>

MusicSlider::MusicSlider(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MusicSlider)
{
    ui->setupUi(this);

    currentPos = 0;

    maxWidth = width();
}

void MusicSlider::setMusicSliderValue(float ratio)
{
    currentPos = maxWidth * ratio;
    moveSlider();
}

MusicSlider::~MusicSlider()
{
    delete ui;
}

void MusicSlider::mousePressEvent(QMouseEvent* event)
{
    currentPos = event->pos().x();
    moveSlider();

    emit setMusicSliderPosition(ui->outLine->width() / (float)ui->inLine->width());
}

void MusicSlider::mouseReleaseEvent(QMouseEvent* event)
{
    currentPos = event->pos().x();
    moveSlider();

    emit setMusicSliderPosition(ui->outLine->width() / (float)ui->inLine->width());
}

void MusicSlider::mouseMoveEvent(QMouseEvent* event)
{
    //鼠标左键按下，才是拖动状态
    if(event->buttons() == Qt::LeftButton)
    {
        currentPos = event->pos().x();

        if(currentPos < 0)
        {
            currentPos = 0;
        }
        else if(currentPos > maxWidth)
        {
            currentPos = maxWidth;
        }

        moveSlider();
    }
}

void MusicSlider::moveSlider()
{
    //更新进度条长度
    ui->outLine->setGeometry(ui->outLine->x(), ui->outLine->y(), currentPos, ui->outLine->height());
}
